/**
 * Copyright (c) 2015-2020, wss 王山山
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.wss.utils.scan;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 扫描文件路径中指定包中的类
 * 
 * @author wss
 *
 */
class PackageScanClasses implements ScanClasses {
	
	@Override
	public List<String> scanPackage(String filePath, String packageName) {
		File file = new File(filePath);
		String[] strs = file.list();
		List<String> classNames = Arrays.stream(strs)
				.filter(e -> isClassFile(e))
				.collect(Collectors.toList());
		return classNames.stream()
				.map(e -> packageName + ScanUtil.DOT + e.substring(0, e.lastIndexOf(ScanUtil.DOT)))
				.map(e -> e.replaceAll(ScanUtil.FILE_PATH_SEPARATOR_PATTERN, ScanUtil.DOT))
				.collect(Collectors.toList());
	}

	@Override
	public List<String> scanPackageRecursive(String filePath, String packageName) {
		File file = new File(filePath);
		List<String> classNames = new ArrayList<>();
		recursiveScan(file, packageName, classNames);
		return classNames.stream()
				.map(e -> e.replaceAll(ScanUtil.FILE_PATH_SEPARATOR_PATTERN, ScanUtil.DOT))
				.collect(Collectors.toList());
	}
	
	/*
	 * 递归扫描子包中的类
	 */
	private void recursiveScan(File file, String packageName, List<String> classNames) {
		Arrays.stream(file.listFiles()).forEach(f -> {
			String fileName = f.getName();
			if (isClassFile(fileName)) {
				classNames.add(packageName + ScanUtil.DOT + fileName.substring(0, fileName.lastIndexOf(ScanUtil.DOT)));
			}
			else if (f.isDirectory()) {
				recursiveScan(f, packageName + ScanUtil.DOT + f.getName(), classNames);
			}
		});
	}
}
